package springboot.doMain;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.Date;

/**
 * wx_group
 */
@Data
@NoArgsConstructor
public class WxGroup implements Serializable {
	/**
	 * 表id
	 */
	private Long id;
	
	/**
	 * api 群ID
	 */
	private String chatId;
	
	/**
	 * 群主
	 */
	private String owner;
	
	/**
	 * 群名
	 */
	private String name;
	
	/**
	 * 客户数量
	 */
	private int clientCnt;
	
	/**
	 * 所有人数
	 */
	private int allCnt;
	
	/**
	 * 创建时间，十位时间戳
	 */
	private int createTime;
	
	/**
	 * 插入时间
	 */
	private Date insertDate;
	
	private static final long serialVersionUID = 1L;
	
	public boolean isEquals(WxGroup wxGroup) {
		return this.owner.equals(wxGroup.getOwner()) &&
						this.name.equals(wxGroup.getName()) &&
						this.allCnt == wxGroup.getAllCnt() &&
						this.clientCnt == wxGroup.getClientCnt();
	}
	
	@Override
	public String toString() {
		return "WxGroup{" +
						"chatId='" + chatId + '\'' +
						", owner='" + owner + '\'' +
						", name='" + name + '\'' +
						", clientCnt=" + clientCnt +
						", allCnt=" + allCnt +
						", createTime=" + createTime +
						'}';
	}
	
	public static WxGroup getInstance(String groupInfoString) {
		if (groupInfoString == null) {
			return null;
		}
		JSONObject jsonObject = JSONObject.parseObject(groupInfoString);
		return new WxGroup(jsonObject);
	}
	
	public WxGroup(JSONObject groupInfo) {
		if (groupInfo == null) {
			return;
		}
		JSONArray jsonArray = JSON.parseArray(groupInfo.getString("member_list"));
		if (jsonArray != null) {
			this.clientCnt = 0;
			this.allCnt = jsonArray.size();
			for (Object object : jsonArray) {
                  /*成员类型。
                  1 - 企业成员
                  2 - 外部联系人*/
				if (JSON.parseObject(String.valueOf(object)).getString("type").equals("2")) {
					this.clientCnt++;
				}
			}
			this.chatId = groupInfo.getString("chat_id");
			this.owner = groupInfo.getString("owner");
			this.name = groupInfo.getString("name");
			this.createTime = Math.toIntExact(groupInfo.getLong("create_time"));
		}
	}
}
